package sign

import (
	"fmt"
	"strings"

	"gitee.com/micro-plat/sas/sas/modules/auth/conf"
	"gitee.com/micro-plat/sas/sas/modules/sign/signfactory"

	"github.com/micro-plat/hydra"
	"github.com/micro-plat/lib4go/types"
)

//Verify 验证签名
func Verify(input map[string]interface{}, key, signName, signType, rsaSType string, conf *conf.AuthConfig) (bool, error) {
	outSign := types.GetString(input[signName])
	delete(input, signName)
	raw := BuildRaw(input, key, signType, &conf.Connect)
	handler, err := signfactory.Get(signType)
	if err != nil {
		return false, err
	}

	rsaHasType := ""
	if strings.EqualFold(signType, "rsa") {
		if _, ok := conf.Params[signType]; !ok {
			return false, fmt.Errorf("未找到rsa相关的配置")
		}
		rsaHasType = types.GetString(conf.Params[signType].Mode, "md5")
	}

	res, err := handler.Verify(outSign, raw, key, rsaSType, rsaHasType)
	if !res || err != nil {
		hydra.G.Log().Infof("raw:%s", strings.ReplaceAll(raw, key, "***"))
	}
	return res, err
}

//Sign 签名
func Sign(raw, key, signType, rsaSType string, conf *conf.AuthConfig) (string, error) {
	handler, err := signfactory.Get(signType)
	if err != nil {
		return "", err
	}

	rsaHasType := ""
	if strings.EqualFold(signType, "rsa") {
		if _, ok := conf.Params[signType]; ok {
			rsaHasType = types.GetString(conf.Params[signType].Mode, "md5")
		} else {
			rsaHasType = "md5"
		}
	}
	return handler.Sign(raw, key, rsaSType, rsaHasType), nil
}
